package org.chen.controller;

import lombok.extern.slf4j.Slf4j;
import org.chen.common.exception.ServiceException;
import org.chen.domain.dto.*;
import org.chen.domain.response.PageResult;
import org.chen.domain.response.Result;
import org.chen.domain.vo.TaskVO;
import org.chen.service.VideoTaskService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/video")
@Slf4j
@Validated
public class VideoTaskController {
    
    @Autowired
    private VideoTaskService videoTaskService;
    
    /**
     * 批量生成视频
     */
    @PostMapping("/generate/batch")
    public Result<List<String>> generateBatchVideos(@RequestBody @Validated BatchGenerateDTO generateDTO) {
        try {
            List<String> taskIds = videoTaskService.createTasks(generateDTO);
            return Result.success(taskIds);
        } catch (ServiceException e) {
            log.error("Generate videos failed", e);
            return Result.error(e.getMessage());
        }
    }

    /**
     * 批量生成视频
     */
    @PostMapping("/generate/batch/ai")
    public Result<List<String>> generateBatchAiVideos(@RequestBody @Validated BatchMultiAvatarGenerateDTO generateDTO) {
        try {
            List<String> taskIds;

            // 根据模式选择不同的处理方法
            if ("single".equals(generateDTO.getMode())) {
                // 单数字人模式，兼容旧版本
                BatchGenerateDTO singleDTO = new BatchGenerateDTO();
                singleDTO.setArticleIds(generateDTO.getArticleIds());
                singleDTO.setConfig(generateDTO.getConfig());

                taskIds = videoTaskService.createTasks(singleDTO);
            } else if ("multiple".equals(generateDTO.getMode())) {
                // 多数字人模式
                taskIds = videoTaskService.createMultiAvatarTasks(generateDTO);
            } else {
                return Result.error("不支持的视频生成模式");
            }

            return Result.success(taskIds);
        } catch (ServiceException e) {
            log.error("Generate videos failed", e);
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 获取任务列表
     */
    @GetMapping("/task/list")
    public Result<PageResult<TaskVO>> getTaskList(TaskQueryDTO query) {
        try {
            PageResult<TaskVO> result = videoTaskService.getTaskList(query);
            return Result.success(result);
        } catch (ServiceException e) {
            log.error("Get task list failed", e);
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 重试任务
     */
    @PostMapping("/task/retry/{taskId}")
    public Result<Void> retryTask(@PathVariable String taskId) {
        try {
            videoTaskService.retryTask(taskId);
            return Result.success();
        } catch (ServiceException e) {
            log.error("Retry task failed", e);
            return Result.error(e.getMessage());
        }
    }

    /**
     * 批量重试任务
     */
    @PostMapping("/task/batch-retry")
    public Result<Void> batchRetryTasks(@RequestBody List<String> taskIds) {
        try {
            videoTaskService.batchRetryTasks(taskIds);
            return Result.success();
        } catch (ServiceException e) {
            log.error("Batch retry tasks failed", e);
            return Result.error(e.getMessage());
        }
    }

    @DeleteMapping("/task/{id}")
    public Result<Void> deleteTask(@PathVariable String id) {
        videoTaskService.deleteTask(id);
        return Result.success();
    }

    @DeleteMapping("/task/batch")
    public Result<Void> batchDeleteTasks(@RequestBody BatchDeleteDTO request) {
        videoTaskService.batchDelete(request.getIds());
        return Result.success();
    }

    @GetMapping("/task/download")
    public void batchDownloadVideos(
            @RequestParam List<String> taskIds,
            HttpServletResponse response
    ) throws IOException {
        // 生成带有时间戳和视频数量的文件名
        String timestamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        String fileName = String.format("videos_%s_%d.zip", timestamp, taskIds.size());

        // 设置响应头
        response.setContentType("application/zip");
        response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
        response.setHeader("Transfer-Encoding", "chunked");

        try {
            videoTaskService.downloadVideos(taskIds, response.getOutputStream());
        } catch (Exception e) {
            log.error("Download videos failed", e);
            throw new ServiceException("下载视频失败: " + e.getMessage());
        }
    }
}